﻿using System.Collections.Generic;
using System.Linq;
using DataScripter.Database;
using DataScripter.Scripting.Filters;

namespace DataScripter.Scripting
{
    public class TableScriptRequest : ITableScriptRequest
    {
        public TableScriptRequest(string tableName, IDatabaseStructure databaseStructure, int requestOrder)
        {
            TableName = tableName;
            RequestOrder = requestOrder;
            TableStructure = databaseStructure.GetTable(TableName);
            Filters = new Dictionary<string, ITableFilter>();
            SpecialFieldTreatments = new Dictionary<string, ISpecialFieldTreatment>();
        }

        public int RequestOrder { get; private set; }

        public ITableStructure TableStructure { get; set; }

        public IDictionary<string, ITableFilter> Filters { get; private set; }

        public string UsedQuery { get; set; }

        public IDictionary<string, ISpecialFieldTreatment> SpecialFieldTreatments { get; private set; }

        public string ProduceFilter()
        {
            return string.Join(" AND ", Filters.Values.Select(f => f.ProduceFilter()).ToArray());
        }

        public string ProduceWhereClause()
        {
            string netWhereClause = ProduceFilter();
            return string.IsNullOrEmpty(netWhereClause) ? string.Empty : " WHERE " + netWhereClause;
        }

        public string TableName { get; private set; }

        public override string ToString()
        {
            return TableName;
        }
    }
}